<template>
  <div class="projectMate">
    <div class="mateCascader">
      <el-cascader
        v-model="cascaderValue"
        :props="defaultProps"
        :options="typeList"
        @change="changeCascader"
      >
      </el-cascader>
    </div>
    <div class="mateEdit">
      <el-row :gutter="20" type="flex">
        <el-col :span="15">
          <NewCard title="材料列表" :border="false">
            <div class="table-box">
              <el-table
                :data="tableList"
                style="width: 100%"
                highlight-current-row
                @row-click="rowClick"
              >
                <el-table-column label="序号" type="index" width="80">
                </el-table-column>
                <el-table-column label="材料名称" width="200">
                  <template slot-scope="scope">
                    <p>{{ scope.row.name ? scope.row.name : "--" }}</p>
                  </template>
                </el-table-column>
                <el-table-column label="材料要求">
                  <template slot-scope="scope">
                    <el-popover
                      placement="top-start"
                      width="300"
                      trigger="hover"
                      :content="scope.row.requirement">
                      <p slot="reference">{{ scope.row.requirement }}</p>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="样本" width="80">
                  <template slot-scope="scope">
                    <!-- materialSampleList -->
                    <p>
                      {{
                        scope.row.materialSampleList.length == 0
                          ? "未上传"
                          : "已上传"
                      }}
                    </p>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 底部按钮 -->
            <!-- <div class="bottomBtn">
              <el-button @click="clickbBtn" v-if="bottomBtnShow">+添加材料</el-button>
              <el-input
                v-model="bottomBtnValue"
                v-else
                @blur="bottomBtnShow = true"
                @keyup.enter.native="addMaterials"
                ref="bottBtn">
              </el-input>
            </div> -->
          </NewCard>
        </el-col>
        <el-col :span="9">
          <NewCard :title="editOrAdd?'编辑':'新增'">
            <div class="editForm">
              <el-form
                ref="form"
                :model="editFrom"
                label-width="100px"
                label-position="left">
                <el-form-item label="材料名称">
                  <el-input
                    v-model="editFrom.name"
                    placeholder="请输入..."
                  ></el-input>
                </el-form-item>
                <el-form-item label="材料要求">
                  <el-input
                    v-model="editFrom.requirement"
                    type="textarea"
                    rows="8"
                    resize="none"
                    placeholder="请输入..."
                  ></el-input>
                </el-form-item>
                <el-form-item label="材料样本">
                  <!-- 图片列表 -->
                  <!-- <div class="uploadImg-list">
                    <div class="img-box" v-for="(img, index) in pictureObj" :key="index">
                      <el-upload
                        :auto-upload="false"
                        class="avatar-uploader"
                        action="#"
                        :show-file-list="false"
                        :on-change="(file, fileList) => {againUpload(file, fileList, index)}">
                        <img :src="img" class="avatar" />
                      </el-upload>
                      <i class="el-icon-error" @click="removeImg(img)" v-hasPermi="['work:materialSample:remove']"></i>
                    </div>
                  </div> -->
                  
                  <!-- 上传按钮 -->
                  <el-upload
                    :auto-upload="false"
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    :on-change="uploadMaterial">
                    <el-button round>点击上传</el-button>
                    <!-- <i class="el-icon-plus avatar-uploader-icon"></i> -->
                  </el-upload>

                  <!-- 文件列表 -->
                  <div class="uploadFlie-list" v-if="editFrom.materialSampleList">
                    <div class="flie-item" v-for="(material,index) in editFrom.materialSampleList" :key="index">
                      <div>
                        <i class="el-icon-document"></i>
                        <p>{{ getMaterialName(material) }}</p>
                      </div>
                      <div>
                        <a :href="material.file" v-if="material.id">
                          <svg-icon icon-class="download"/>
                        </a>
                        <i class="el-icon-delete" @click="removeImg(material)" v-hasPermi="['work:materialSample:remove']"></i>
                      </div>
                    </div>
                  </div>
                  
                </el-form-item>
              </el-form>
            </div>
            <SubBtn v-hasPermi="['work:projectMaterial:edit']">
              <template slot="btn">
                <el-button round @click="addForm">新增</el-button>
                <el-button round @click="removeForm" v-hasPermi="['work:projectMaterial:remove']">删除</el-button>
                <el-button type="primary" round @click="saveForm" :disabled="!isCheck" v-hasPermi="['work:projectMaterial:add']">保存</el-button>
              </template>
            </SubBtn>
          </NewCard>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import NewCard from "@/wss/components/newCard.vue";
import ComTable from "@/wss/components/comTable.vue";
import SubBtn from "@/wss/components/subBtn.vue";
import {
  changeBase64Fn,
  changeFileToURLFn,
  getFileFromUrl,
} from "@/wss/utils/wss.js";
import { getProjectTypelistApi } from "@/wss/newApi_3-24/work/projectType.js";
import {
  getProjectMaterialListApi,
  editProjectMaterialApi,
  addProjectMaterialApi,
  removeProjectMaterialApi,
  removeMaterialSampleApi,
} from "@/wss/newApi_3-24/work/projectMaterial.js";
import debounce from "lodash/debounce";
export default {
  name: "Materials",
  components: { NewCard, ComTable, SubBtn },
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "name",
        value: "id",
      },
      typeList: [], //全部类别数据
      cascaderList: [], //级联两层类别数据
      cascaderValue: [], // 选择的类别

      bottomBtnShow: true, //底部按钮
      bottomBtnValue: "", //底部输入值

      editOrAdd: false,//当前是true编辑还是false新增

      // 分页参数
      pageing: { pageNum: 1, pageSize: 100, total: 0 },
      // 表格数据
      tableList: [],

      // 表单数据
      editFrom: {
        name: "",
        requirement: "",
        status: "0",
        typeId: "",
        materialSampleList: [],
      },
      // 已上传文件转成文件流形式的数据
      fileRaw: [],
      //上传的图片
      pictureObj: [],
      // 上传图片列表
      fileList: [],

      isCheck: true,// 判断当前点击保存是否已经返回请求
    };
  },
  async mounted() {
    await this.getProjectTypelist(); //获取项目类型列表
    this.getProjectMaterialList(); //获取所选的项目类型下的项目材料
  },
  methods: {
    // 级联选择器发生变化的时候
    changeCascader() {
      this.getProjectMaterialList(); //获取所选的项目类型下的项目材料
    },

    // 获取项目类型列表
    async getProjectTypelist() {
      let { code, rows } = await getProjectTypelistApi();
      if (code != 200) return;
      this.typeList = JSON.parse(JSON.stringify(rows));

      // 级联两层类别数据
      this.cascaderList = this.typeList;
      this.cascaderList.forEach((i) => {
        i.children.forEach((k) => this.$delete(k, "children"));
      });
      // 级联选择器默认值
      this.cascaderValue.push(this.typeList[0].id);
      this.cascaderValue.push(this.typeList[0].children[0].id);
    },

    //获取所选的项目类型下的项目材料
    async getProjectMaterialList() {
      //获取所选的项目类型最后一个类型的id
      let typeId = this.cascaderValue[this.cascaderValue.length - 1];
      let result = await getProjectMaterialListApi({ typeId });
      if (result.code == 200) {
        this.tableList = result.rows;
      }
    },

    //点击表格某一行 把某一行的数据赋值给编辑表单
    rowClick(row) {
      this.editOrAdd = true //显示编辑标题
      //清空之前编辑的数据
      this.editFrom = {
        name: "",
        requirement: "",
        status: "0",
        typeId: "",
        materialSampleList: [],
      };
      this.pictureObj = [];
      this.fileRaw = [];
      this.fileList = [];
      //获取typeID
      this.editFrom.typeId = this.cascaderValue[this.cascaderValue.length - 1];
      // 合并数组
      let newObj = Object.assign(this.editFrom, row);
      this.editFrom = newObj;
      //获取材料样本的地址回显
      this.editFrom.materialSampleList.forEach((item) => {
        this.pictureObj.push(item.file);
      });

      //把已上传的图片转成文件流的形式 fileRaw *****************
      this.fileRaw = [] //加之前先清除
      this.editFrom.materialSampleList.forEach((item) => {
        //获取文件名称
        if(item.id){
          let arr = item.file.split("/")
          let name = arr[arr.length-1]
          let fileName =  name

          //转成文件流
          getFileFromUrl(item.file,fileName)
          .then((response)=>{
            let file = response
            this.fileRaw.push(file);
          })
        }
      });
      //把已上传的图片转成文件流的形式 fileRaw ***************** end
    },

    // 点击添加材料
    clickbBtn() {
      //显示输入框
      this.bottomBtnShow = false;
      //输入框自动获取焦点
      this.$nextTick(() => {
        this.$refs.bottBtn.focus();
      });
    },

    //输入框按回车的回调
    async addMaterials() {
      if (this.bottomBtnValue) {
        await this.addProjectMaterial(); //添加项目材料
        this.getProjectMaterialList(); //更新项目材料列表
        //隐藏输入框
        this.bottomBtnShow = true;
        this.bottomBtnValue = "";
      } else {
        this.$message({ type: "warning", message: "请输入材料名称" });
      }
    },

    //上传图片的回调
    uploadMaterial(file, fileList) {
      //上传判断
      const isFormat =
        file.raw.type === "image/jpeg" ||
        file.raw.type === "image/png" ||
        file.raw.type === "application/pdf" ||
        file.raw.type === "application/msword" ||
        file.raw.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
        file.raw.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const isPostfix = 
          file.raw.name.split('.')[1] === "jpg" ||
          file.raw.name.split('.')[1] === "jpeg" || 
          file.raw.name.split('.')[1] === "png" || 
          file.raw.name.split('.')[1] === "pdf" ||
          file.raw.name.split('.')[1] === "doc" || 
          file.raw.name.split('.')[1] === "docx" || 
          file.raw.name.split('.')[1] === "xlsx";
      const isLt2M = file.raw.size / 1024 / 1024 < 20;

      if (!isFormat || !isPostfix) {
        this.$message.error("上传样本只能是 JPG/PNG/DOC/DOCX/PDF/XLSX 格式!");
        return;
      } else {
        if (!isLt2M) {
          this.$message.error("上传样本大小不能超过 20MB!");
          return;
        } else {
          // if (fileList && fileList.length > 1) {
          //   fileList.shift();
          // }
          this.fileList.push(file);
          // this.pictureObj.push(URL.createObjectURL(file.raw));
          // 把文件放到修改文件表里面
          this.editFrom.materialSampleList.push(file)
        }
      }
    },

    // 点击图片重新上传
    againUpload(file, fileList, index){
      // //上传判断
      const isJPGPNG =
        file.raw.type === "image/jpeg" || file.raw.type === "image/png";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      if (!isJPGPNG) {
        this.$message.error("上传样本只能是 JPG/PNG 格式!");
        return;
      } else {
        if (!isLt2M) {
          this.$message.error("上传样本大小不能超过 2MB!");
          return;
        } else {

          this.fileRaw[index] = file.raw
          this.$set(this.pictureObj,index,URL.createObjectURL(file.raw))
          // this.pictureObj[index] = URL.createObjectURL(file.raw)
        }
      }
    },

    // 编辑项目材料的接口
    async editProjectMaterial() {
      // 创建一个form表单
      let editFrom = this.editFrom;
      let formDate = new FormData();
      //项目材料
      formDate.set("name", editFrom.name);
      formDate.set("typeId", editFrom.typeId);
      formDate.set("requirement", editFrom.requirement);
      formDate.set("status", editFrom.status);
      formDate.set("createBy", editFrom.createBy);
      formDate.set("createTime", editFrom.createTime);
      formDate.set("id", editFrom.id);
      this.fileRaw.forEach((item, i) => {
        formDate.append(`file`, item);
      });
      this.fileList.forEach((item, i) => {
        formDate.append(`file`, item.raw);
      });

      //打印formDate
      // for (var key of formDate.entries()) {
      //     console.log(key[0] + ', ' + key[1]);
      // }

      //发请求
      let result = await editProjectMaterialApi(formDate);
      if (result.code == 200) {
        this.$message({
          message: "编辑成功！",
          type: "success",
        });
      } else {
        this.$message.error("编辑失败!");
      }
    },

    // 点击新增按钮
    addForm(){
      this.editOrAdd = false //显示新增标题
      //清空之前编辑的数据
      this.editFrom = {
        name: "",
        requirement: "",
        status: "0",
        typeId: "",
        materialSampleList: [],
      };
      this.pictureObj = [];
      this.fileRaw = [];
      this.fileList = [];
    },

    //点击保存按钮
    saveForm: debounce(async function() {
      if(this.editOrAdd){
        // 当前是编辑*************
        if (!this.editFrom.id) {
          this.$message({
            message: "请选择项目材料",
            type: "warning",
          });
        } else {
          this.isCheck = false //先不给点击保存
          await this.editProjectMaterial(); //编辑接口
          await this.getProjectMaterialList(); //重新获取项目材料
          this.isCheck = true //可以点击保存了
        }
      }else{
        // 当前是新增*************
        // this.fileList.length<1
        if (!this.editFrom.name || !this.editFrom.requirement) {
          this.$message({
            message: "请输入完整的项目材料",
            type: "warning",
          });
        } else {
          this.isCheck = false //先不给点击保存
          await this.addProjectMaterial(); //添加项目材料
          await this.getProjectMaterialList(); //更新项目材料列表
          this.isCheck = true //可以点击保存了
        }
      }
    },1000),

    //添加项目材料
    async addProjectMaterial() {
      //获取所选的项目类型最后一个类型的id
      let typeId = this.cascaderValue[this.cascaderValue.length - 1];
      let name = this.bottomBtnValue;
      let editFrom = this.editFrom
      // 创建一个form表单
      let formDate = new FormData();
      //项目材料
      formDate.set("name", editFrom.name);
      formDate.set("typeId", typeId);
      formDate.set("requirement", editFrom.requirement);
      formDate.set("status", editFrom.status);
      this.fileList.forEach((item, i) => {
        formDate.append(`file`, item.raw);
      });
      let result = await addProjectMaterialApi(formDate);
      // console.log(result);
      if (result.code == 200) {
        this.$message({
          message: "添加成功！",
          type: "success",
        });
        //清空之前编辑的数据
        this.editFrom = {
          name: "",
          requirement: "",
          status: "0",
          typeId: "",
          materialSampleList: [],
        };
        this.pictureObj = [];
        this.fileRaw = [];
        this.fileList = [];
      } else {
        this.$message.error("添加失败!");
      }
    },

    //删除按钮的回调
    async removeForm() {
      if (!this.editFrom.id) {
        this.$message({
          message: "请选择项目材料",
          type: "warning",
        });
      } else {
        await this.removeProjectMaterial(); //删除按钮的接口
        this.getProjectMaterialList(); //重新获取项目材料
      }
    },

    //删除按钮的接口
    async removeProjectMaterial() {
      let id = this.editFrom.id;
      let result = await removeProjectMaterialApi(id);
      if (result.code == 200) {
        this.$message({
          message: "删除成功！",
          type: "success",
        });
        //清空之前编辑的数据
        this.editFrom = {
          name: "",
          requirement: "",
          status: "0",
          typeId: "",
          materialSampleList: [],
        };
        this.pictureObj = [];
        this.fileRaw = [];
        this.fileList = [];
      } else {
        this.$message.error("删除失败!");
      }
    },

    // 删除材料样本的回调
    async removeImg(material) {
      // 根据img路径去拿到当前点击删除的项目材料样本id
      // this.editFrom.materialSampleList.forEach((item) => {
      //   if (item.file == img) {
      //     id = item.id;
      //   }
      // });
      // 有id才去删除，没有的话就在前端找到删掉
      let id = material.id;
      let index = this.editFrom.materialSampleList.indexOf(material);// 获得下标
      this.editFrom.materialSampleList.splice(index,1)// 根据下标去删数据
      this.fileRaw.splice(index,1)// 根据下标去删数据

      let flieindex = this.fileList.indexOf(material);// 获得下标
      this.fileList.splice(flieindex,1)// 根据下标去删数据


      if(id){
        await this.removeMaterialSample(id); // 删除材料样本的接口
        await this.getProjectMaterialList(); //重新获取项目材料
      }

      //更新显示的材料样本
      // this.pictureObj.splice(this.pictureObj.indexOf(img), 1);
    },

    // 删除材料样本的接口
    async removeMaterialSample(id) {
      let result = await removeMaterialSampleApi(id);
      if (result.code == 200) {
        this.$message({
          message: "删除成功！",
          type: "success",
        });
      } else {
        this.$message.error("删除失败!");
      }
    },

    // 获取项目材料的名称
    getMaterialName(material){
      if(material.file){
        let arr = material.file.split("/")
        let name = arr[arr.length-1]
        return name
      }else{
        return material.name
      }
    },
  },
};
</script>

<style scoped>
.projectMate {
  height: 100%;
}
.projectMate .el-card {
  position: relative;
}
.mateEdit >>> .el-card__body {
  height: 100%;
}
.mateEdit >>> .el-card__body > div {
  height: 92%;
  overflow-y: auto;
}
.mateEdit >>> .el-card__body > div::-webkit-scrollbar {
  width: 0;
}

.table-box {
  margin-bottom: 80px;
}

/* 级联选择器 */
.mateCascader {
  height: 40px;
  margin-bottom: 20px;
}
.mateCascader .el-cascader{
  width: 320px;
  padding: 0 10px;
  border-radius: 6px;
  background-color: #F5F6F8;
}
::v-deep .el-cascader .el-input__inner {
  border: 0;
  background-color: transparent;
  padding-left: 0;
  font-size: 20px;
  font-weight: 600;
  color: #2e3f5e;
}
::v-deep .el-cascader .el-icon-arrow-down {
  color: #2e3f5e;
}
::v-deep .el-cascader .el-icon-arrow-down:before {
  content: "\E790";
}

/* 表格数据 */
.mateEdit {
  height: calc(100% - 60px);
}
.mateEdit .el-row {
  height: 100%;
}


/* 表格样式 */
.el-table {
  margin-bottom: 30px;
}
::v-deep .el-table .el-table__body{
  table-layout: fixed !important;
}
::v-deep .el-table .el-table__header-wrapper th {
  background-color: #fff;
}
::v-deep .el-table th.is-leaf {
  border-top: 1px solid #efefef;
  border-bottom: 1px solid #efefef;
}
::v-deep .el-table th > .cell {
  font-size: 12px;
  color: #909aaa;
}
::v-deep .el-table__body tr.current-row > td {
  background-color: #ebecf0;
}
::v-deep .el-table .cell,
::v-deep .el-table .cell p {
  margin: 0;
  font-size: 14px;
  color: #2e3f5e;
  overflow:hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow:ellipsis;
}
::v-deep .el-table .cell .el-button {
  color: #f87a23;
}
::v-deep .el-table .cell .el-table__expand-icon i::before {
  content: "\E791";
}
::v-deep .el-table td {
  /* border-bottom: 0; */
}
::v-deep .el-table td .islight {
  color: #f87a23;
}
::v-deep .el-table .el-table__expanded-cell[class*="cell"] {
  padding: 0;
}
::v-deep .el-table__expanded-cell .el-table::before {
  height: 0;
}
::v-deep .el-table__expanded-cell .el-table th.is-leaf {
  border-top: 0;
}
::v-deep .el-table__expanded-cell .el-table td {
  border-bottom: 0;
  padding: 6px 0;
}

::v-deep .el-table__footer-wrapper tbody td {
  background-color: #fff;
  font-weight: bold;
  color: #2e3f5e;
}

/* 添加材料 */
.bottomBtn {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 9;
}
.bottomBtn .el-button {
  width: 100%;
  border: 0;
  border-top: 1px solid #ecedf0;
  background-color: #f8f8f8;
  line-height: 25px;
  color: #606e84;
}
.bottomBtn .el-input {
  width: 100%;
}
::v-deep .bottomBtn .el-input .el-input__inner {
  height: 46px;
  line-height: 46px;
  border: 0;
  border-top: 1px solid #ecedf0;
  background-color: #f8f8f8;
  text-align: center;
}

/* 编辑 */
.editForm {
  margin-bottom: 80px;
  margin-top: 20px;
}
.editForm >>> .el-textarea__inner {
  font-family: Microsoft Yahei;
}

/* 上传 */
.expertRev .el-button {
  position: absolute;
  top: 10px;
  right: 20px;
  padding: 8px 10px;
  font-size: 13px;
}
::v-deep .avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  width: 100%;
  text-align: left;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.uploadImg-list .img-box {
  position: relative;
  margin-bottom: 15px;
}
.uploadImg-list img {
  display: block;
  width: 100%;
}
.uploadImg-list .img-box > i {
  position: absolute;
  right: 10px;
  top: 10px;
  z-index: 9;
  opacity: 0;
  transition: all 0.3s;
  cursor: pointer;
}
.uploadImg-list .img-box:hover > i {
  opacity: 1;
}
.uploadImg-list .img-box > i:hover {
  color: #f87a23;
}

/* 文件列表 */
.uploadFlie-list{
  margin-bottom: 20px;
}
.uploadFlie-list p{
  margin: 0;
  padding: 0;
}
.uploadFlie-list .flie-item{
  width: 100%;
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #EFEFEF;
  line-height: 40px;
  margin-bottom: 10px;
}
.uploadFlie-list .flie-item>div{
  display: flex;
  align-items: center;
  color: #aaa;
  width: calc(100% - 50px);
}
.uploadFlie-list .flie-item>div:first-child i{
  margin-right: 10px;
}
.uploadFlie-list .flie-item>div:first-child p{
  width: calc(100% - 24px);
  overflow:hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow:ellipsis;
}
.uploadFlie-list .flie-item>div:last-child{
  width: 50px;
}
.uploadFlie-list .flie-item p{
  color: #666;
}
.uploadFlie-list .flie-item>div:last-child i,
.uploadFlie-list .flie-item>div:last-child svg{
  margin-left: 10px;
  cursor: pointer;
  font-size: 15px;
}
/* 文件列表 end */

::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  line-height: 130px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

/* 右侧按钮样式 */
::v-deep .subBtn {
  padding: 8px 30px;
}
::v-deep .subBtn .el-button {
  width: 100px;
  padding: 8px 0;
  font-size: 14px;
  color: #606e84;
}
::v-deep .subBtn .el-button--primary {
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
}
::v-deep .subBtn .el-button--primary:hover {
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
}
</style>
<style>
.el-cascader-node.in-active-path,
.el-cascader-node.is-selectable.in-checked-path,
.el-cascader-node.is-active {
  color: #f87a23;
}
</style>